package com.zk.babala.activity;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.zk.babala.R;
import com.zk.babala.util.LineUtil;

/**
 * @Author: zhangke
 * @Date: 2025/8/11 14:28
 */
public class CookiesWebViewActivity extends Activity {
    private WebView webView;
    private CookieManager cookieManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cookies_webview_actity);
        // 初始化CookieManager
        cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        webView = findViewById(R.id.cookies_webview);

        // 启用JavaScript（如果需要）
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 获取传递的URL
        String url = getIntent().getStringExtra("url");
        if (url != null) {
            webView.loadUrl(url);
        }
        // 设置WebViewClient以在WebView内打开链接
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 页面加载完成后获取cookies
                setCookiesForUrl(url);
            }
        });
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    /**
     * 获取所有cookies（Android 5.0及以上）
     */
    private void setCookiesForUrl(String url) {
        LineUtil.getLineUtil().setLineCookies(cookieManager.getCookie(url));
    }

}
